import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.OutputChannel
import java.net.URL
import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * Message to tell GoogleSearchActor to start performing a search.
 */
case class DoSearch(query: String)

/**
 * Actor that listens for DoSearch(query) messages, and fetches the search results from Google.
 *
 * Sends a GetPageSize(query, url) message for each result to the GetPageSizeActor.
 * Also sends an ExpectUrls(query, numberOfUrls) message to SummaryActor so it knows how long to wait for.
 */
class GoogleSearchActor(getPageSizeActor: OutputChannel[GetPageSize], summaryActor: OutputChannel[ExpectUrls]) extends Actor {

  def getSearchResultsAsHtml(query : String) : String = {
	val httpQuery = "http://www.google.com/search?q=" + query;
	val httpURL = new URL(httpQuery)
	val in = new BufferedReader(
				new InputStreamReader(
				httpURL openStream));
	var ret_string = ""

	var inputLine = in.readLine();
	while (inputLine != null) {
		ret_string += inputLine
		inputLine = in.readLine();
	}

	in close;

	ret_string;
  }

  def act() {
    loop {
      react {

        case DoSearch(query) => {
          println("GoogleSearchActor received DoQuery('" + query + "')")
          // Create the URL containing the query
	val resultData = getSearchResultsAsHtml(query)
	println("Results: " + resultData);
	
	
	// Connect to google.com and fake a HTTP request containing the query
	// (or - use HTTP library to send it)
	// Get the contents of the results page and parse it for URLs
          
          // TODO: Replace this fake implementation with the real code!
          Thread.sleep(500)
          val urls = List(
              "http://icanhascheezburger.com/",
              "http://www.bing.com/",
              "http://www.msn.com/",
              "http://twitter.com/",
              "http://www.facebook.com/",
              "http://www.sun.com/",
              "http://slashdot.org/",
              "http://www.ebay.com/",
              "http://slashdot.org/"
          )

          summaryActor ! ExpectUrls(query, urls.size)
          urls.foreach({ url => getPageSizeActor ! GetPageSize(query, url) })
        }

      }
    }
  }

}
